import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {environment} from '../../../environments/environment';
import {WebSocketMessage} from './WebSocketMessage';

@Injectable({
  providedIn: 'root'
})

export class ChatService {
  private ws: WebSocket | null = null;
  private messageSubject = new Subject<WebSocketMessage>();
  private roomId: string = ''; // 存储当前房间号
  private clientId: string = '';
  private type: 'create' | 'join' | 'chat' | 'code' = 'chat'; // 存储当前的操作类型（创建房间/加入房间/聊天/同步代码）

  constructor() {}

  // 创建房间
  createRoom(roomId: string, clientId: string) {
    this.roomId = roomId;
    this.type = 'create'; // 设置操作类型为创建房间
    this.clientId = clientId;
    this.connect();
  }

  // 加入房间
  joinRoom(roomId: string, clientId: string) {
    this.roomId = roomId;
    this.type = 'join'; // 设置操作类型为加入房间
    this.clientId = clientId;
    this.connect();
  }

  // 连接到指定房间
  private connect() {
    // 验证房间号（确保是6位数字）
    if (!/^\d{6}$/.test(this.roomId)) {
      console.warn('房间号必须是6位数字');
      return;
    }

    // 连接到指定房间
    this.ws = new WebSocket(environment.apiUrl.replace(/^http/, 'ws') + '/chat');

    this.ws.onmessage = (event) => {
      const message = JSON.parse(event.data);

      // 判断是否是错误消息
      if (message.subtype === 'error') {
        console.warn(message);
        this.messageSubject.next(message);

        // 断开连接，等待用户重新输入正确的房间号
        this.ws?.close();
        return;
      }

      // 正常消息处理
      this.messageSubject.next(message);
    };

    // 在连接建立后发送创建房间/加入房间/聊天消息的请求
    this.ws.onopen = () => {
      const message = {
        type: this.type,
        roomId: this.roomId,
        clientId: this.clientId,
      };

      // 发送消息
      this.ws?.send(JSON.stringify(message));
    };
  }

  leaveRoom() {
    if (this.ws) {
      this.ws.close(); // 主动断开连接
      this.ws = null;
      this.roomId = '';
      this.clientId = '';
    }
  }

  // 发送消息到当前房间
  sendMessage(msg: string) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      const message = {
        type: 'chat',
        roomId: this.roomId,
        clientId: this.clientId,
        message: msg,
      };
      this.ws.send(JSON.stringify(message));
    } else {
      console.warn('WebSocket is not open.');
    }
  }

  sendDelta(delta: object, codeHash: string, cursor?: { row: number, column: number }) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      const message = {
        type: 'code',
        action: 'update',
        roomId: this.roomId,
        clientId: this.clientId,
        codeHash: codeHash,
        message: delta,
        cursor: cursor
      };
      this.ws.send(JSON.stringify(message));
    } else {
      console.warn('WebSocket is not open.');
    }
  }

  sendFullCode(code: string) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      const message = {
        type: 'code',
        action: 'fullCode',
        roomId: this.roomId,
        clientId: this.clientId,
        message: code,
      };
      this.ws.send(JSON.stringify(message));
    } else {
      console.warn('WebSocket is not open.');
    }
  }

  // 获取消息
  getMessages(): Observable<WebSocketMessage> {
    return this.messageSubject.asObservable();
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.close();
    }
  }
}
